package plugin.demo.apt.processor;

import com.google.auto.service.AutoService;
import com.sun.org.apache.bcel.internal.generic.ASTORE;
import jdk.nashorn.internal.ir.debug.ASTWriter;
import plugin.demo.apt.annotations.Code;
import plugin.demo.apt.annotations.Print;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/5/13 下午2:30
 * @UpdateDate:
 * @Description:
 */
@AutoService(Processor.class)
public class CodeProcessor extends AbstractProcessor{

    private Filer filer;
    private Elements elements;
    private Types types;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        this.filer = processingEnv.getFiler();
        this.elements = processingEnv.getElementUtils();
        this.types = processingEnv.getTypeUtils();
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> supportAnnotationTypes = new HashSet<>();
        supportAnnotationTypes.add(Code.class.getName());
        return supportAnnotationTypes;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //获取所有被Code标注的类
        Set<? extends Element> annotatedWith = roundEnv.getElementsAnnotatedWith(Code.class);

//        AST ast = AST.newAST(AST.JLS3);
//        CompilationUnit compilationUnit = ast.newCompilationUnit();
//        TypeDeclaration programClass = ast.newTypeDeclaration();
//        programClass.setName(ast.newSimpleName("MyController"));
//        // 设定类或接口的修饰类型public
//        programClass.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
//        // 将创建好的类添加到文件
//        compilationUnit.types().add(programClass);
//
//        for (Element element : annotatedWith) {
//            Writer writer = null;
//            try {
//                JavaFileObject sourceFile = filer.createSourceFile((TypeElement.class.cast(element.getEnclosingElement()).getQualifiedName()) + "$Generic");
//                writer = sourceFile.openWriter();
//                PrintWriter printWriter = new PrintWriter(writer);
//                printWriter.print();
//
//            }catch (Throwable e){
//
//            }
//
//        }

        //该方法返回ture表示该注解已经被处理, 后续不会再有其他处理器处理; 返回false表示仍可被其他处理器处理.
        return true;
    }
}